import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { TransferManageContext, IAllotActionEnum } from '../mconfig';
import { getTableColumns } from '../mconfig/ModalColumns';
import { Button, Col, Row, Spin, message } from 'antd';
import { getColorTextLoadMap, getKeyRouter, getLoadMapList, getSelectDataMapList, getTenantID, onCloseModalCommon } from '@/utils';
import { showTotalInfo } from '@/common/constVariable';
import { ILoadMapTypeAll } from '@/common';
import { materialTableService } from '../services';
import { UpdateTableCommon } from '../mview/UpdateTableCommon';
import _ from 'lodash';

export const OpenMaterialModal: React.FC<any> = ({ onClose, isShowModal, departmentID }) => {
  /**弹框的ref*/
  const addMaterialRef: Ref<IOneModalRef> = useRef(null);

  /**样式类名*/
  const styleFixCls = 'contract-styfixcls-';

  // /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`, //资产存放地点
    // `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
  ]);

  // /** 资产类型 */
  // const assetTypeList = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`], 'name', 'id', true);

  /** 获取上下文 */
  const {
    materielList,
    curRes,
    rightTableProps: { materielForm },
    allotDispatch,
  } = useContext(TransferManageContext);

  /** 获取列表 */
  const { data, loading, params, searchList, pagination, getManageData } = materialTableService(curRes, departmentID);

  /** 暂时保存选中的值 */
  const [checkMaterialList, setCheckMaterialList] = useState<Record<string, any>[]>([]);

  /** 表格数据 */
  const [dataSource, setDataSource] = useState<Record<string, any>[]>([]);

  // // 处理列表数据id
  // const processData = (data: any) => {
  //   const newData = data?.rows.map((item: any) => {
  //     item.materialOrAssetId = item.id;
  //     return item;
  //   });
  //   return newData;
  // };

  useMemo(() => {
    let dataRow: Record<string, any>[] = [];
    if (data?.rows?.length >= 0) {
      dataRow = data?.rows.map((item: any) => {
        item.materialOrAssetId = item.id;
        item.location = '';
        item.locationInfo = '';
        item.locationName = '';
        return item;
      });
      if (checkMaterialList.length !== 0) {
        for (let i = 0; i < checkMaterialList.length; i++) {
          let idx = dataRow.findIndex((item: Record<string, any>) => {
            return item.materialOrAssetId === checkMaterialList[i].materialOrAssetId;
          });
          if (idx !== -1) {
            dataRow[idx].quantityOrArea = Number(checkMaterialList[i].quantityOrArea);
            dataRow[idx].location = checkMaterialList[i].location;
            dataRow[idx].locationName = checkMaterialList[i].location;
            dataRow[idx].locationInfo = checkMaterialList[i].locationInfo;
          }
        }
      }
      setDataSource(dataRow);
    }
    return dataRow;
  }, [data]);

  const handleCancel = () => {
    onClose();
  };

  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /**重置方法*/
  const onReset = (reqParams) => {
    getManageData({ ...reqParams });
  };

  /**搜索方法*/
  const onSearch = (reqParams) => {
    getManageData({ ...reqParams });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo) => {
    const tempArr = _.cloneDeep(dataSource);

    for (let i = 0; i < tempArr.length; i++) {
      tempArr[i].selected = selectInfo?.some((item) => item.id === tempArr[i].id);
    }
    setDataSource(tempArr);
    setCheckMaterialList(selectInfo);
  };

  const batchSyncData = (text, record) => {
    let arrData = _.cloneDeep(dataSource);
    arrData?.map((item: Record<string, any>) => {
      let arr = checkMaterialList.find((i) => {
        return i.id == item.id;
      });
      if (arr && !item[text]) {
        item[text] = record[text];
        if (text == 'locationName') item.location = record[text];
      }
    });
    setDataSource(arrData);

    let arrChecked = _.cloneDeep(checkMaterialList);
    arrChecked?.map((item: Record<string, any>) => {
      if (!item[text]) item[text] = record[text];
      if (text == 'locationName') item.location = record[text];
    });
    setCheckMaterialList(arrChecked);
  };

  /** 修改存放地点 */
  const changeLocation = (id: string | number, value: string) => {
    /** 修改表格存放地点 */
    let idx = dataSource.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });

    if (idx !== -1) {
      let arr = _.cloneDeep(dataSource);
      arr[idx].locationName = value;
      arr[idx].location = value;
      setDataSource(arr);
    }

    /** 修改选中存放地点 */
    let checkIdx = checkMaterialList.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });

    if (checkIdx !== -1) {
      let arr = _.cloneDeep(checkMaterialList);
      arr[checkIdx].location = value;
      arr[checkIdx].locationName = value;
      setCheckMaterialList(arr);
    }
  };

  /** 修改详细地址 */
  const changeLocationInfo = (id: string | number, value: string) => {
    /** 修改表格存放地点 */
    let idx = dataSource.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });
    if (idx !== -1) {
      let arr = _.cloneDeep(dataSource);
      arr[idx].locationInfo = value;
      setDataSource(arr);
    }

    /** 修改选中存放地点 */
    let checkIdx = checkMaterialList.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });
    if (checkIdx !== -1) {
      let arr = _.cloneDeep(checkMaterialList);
      arr[checkIdx].locationInfo = value;
      setCheckMaterialList(arr);
    }
  };

  const getTableModalColumn: any = useMemo(() => {
    return getTableColumns({
      loadMapInfo,
      mapLoading,
      changeLocation,
      changeLocationInfo,
    });
  }, [materielList]);

  const handleSave = () => {
    if (checkMaterialList && checkMaterialList?.length > 0) {
      // 存储到仓库
      allotDispatch({
        type: IAllotActionEnum.SELECT_MATERIEL,
        payload: [...checkMaterialList],
      });
      onCloseModalCommon(addMaterialRef);
    } else {
      message.error('请至少选择一个物资');
    }
    return;
  };

  useEffect(() => {
    setCheckMaterialList(materielList);
  }, [isShowModal]);

  const desabledNextBtn = useMemo(() => {
    if (
      checkMaterialList?.length != 0 &&
      checkMaterialList?.every((item: Record<string, any>) => item.locationName) &&
      checkMaterialList?.every((item: Record<string, any>) => item.locationInfo)
    ) {
      return false;
    } else {
      return true;
    }
  }, [checkMaterialList]);

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={addMaterialRef}
        title={'添加需求资产'}
        width={document.body.clientWidth * 0.65}
        bodyStyle={{
          height: document.body.clientHeight * 0.55,
          padding: 10,
        }}
        onCancel={handleCancel}
        footer={[
          <Button
            key="back"
            loading={false}
            onClick={() => {
              onCloseModalCommon(addMaterialRef);
            }}
          >
            取消
          </Button>,
          <Button key="submit" type="primary" loading={false} onClick={handleSave} disabled={desabledNextBtn}>
            添加
          </Button>,
        ]}
      >
        <Spin spinning={false}>
          <Row className={`${styleFixCls}materialModal`}>
            <Col span={24}>
              <UpdateTableCommon
                styleFixCls={styleFixCls}
                searchProps={{
                  searchList,
                  onReset,
                  onSearch,
                }}
                selectTablePorps={{
                  onSelectTable,
                  selectRowObjList: checkMaterialList,
                  selectType: 'checkbox',
                }}
                tableProps={{
                  columns: getTableColumns({
                    batchSyncData,
                    loadMapInfo,
                    mapLoading,
                    changeLocation,
                    changeLocationInfo,
                  }),
                  loading,
                  dataSource: dataSource,
                  pagination,
                  onPageChange,
                  rowKey: 'materialOrAssetId',
                  tableTotalShow: (total: any, range: any) => {
                    return (
                      <div
                        style={{
                          display: 'flex',
                          width: '100%',
                          justifyContent: 'space-between',
                        }}
                      >
                        <div>
                          已选择<strong style={{ color: 'red' }}> {checkMaterialList?.length} </strong>条物料
                        </div>
                        <div>{showTotalInfo(total, range)}</div>
                      </div>
                    );
                  },
                }}
              />
            </Col>
          </Row>
        </Spin>
      </OneModal>
    </>
  );
};
